#include <stdx/all.h>

vector<string> applist = {
	"$SOURCE_HOME/webapp/cpp/.bin/cleanup",
	"$SOURCE_HOME/webapp/cpp/.bin/sendmail",
	"$SOURCE_HOME/webapp/app/mapdata/cpp/.bin/syncweatherinfo"
};

class MainApplication : public Application
{
private:
	string getcwd(const string& path)
	{
		string str = path::parent(path);
		
		if (path::name(str) == ".bin") str = path::parent(str);

		return str;
	}
	
public:
	bool main()
	{
		char cmd[1024];
		char buffer[1024];

		LogThread::Instance()->init("log");
		
		LogTrace(eINF, "enter monitoring loop ...");
		
		for (auto& path : applist) path = stdx::translate(path);

		while (true)
		{
			vector<ProcessData> vec;

			if (Process::GetSystemProcessList(vec) > 0)
			{
				set<string> tmp;
				
				tmp.insert(applist.begin(), applist.end());

				for (auto& item : vec)
				{
					auto it = std::find(applist.begin(), applist.end(), item.path);
					
					if (it == applist.end()) continue;
					
					tmp.erase(item.path);
				}
				
				for (auto& item : tmp)
				{
					snprintf(cmd, sizeof(cmd), "cd \"%s\" && daemon \"%s\"", getcwd(item).c_str(), item.c_str());
					
					if (System(cmd) >= 0)
					{
						LogTrace(eIMP, "start service[%s] success", path::name(item).c_str());
					}
					else
					{
						LogTrace(eERR, "start service[%s] failed", path::name(item).c_str());
					}
				}
			}
			
			sleep(5);
		}

		return true;
	}
};

START_APP(MainApplication)